﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.Practices.Composite.Events;
using StockholmsStad.Runtime.Serialization.DataContract;
using StockholmsStad.Windows.UI.Modules.Couple.BusinessEntities;
using StockholmsStad.Windows.UI.Modules.Couple.Interfaces;
using StockholmsStad.Windows.UI.Modules.Couple.Models;

namespace StockholmsStad.Windows.UI.Modules.Couple.Views
{
    /// <summary>
    /// Interaction logic for TabItemCeremonyView.xaml
    /// </summary>
    public partial class TabItemCeremonyView : ICeremonyView
    {
        private int loadedTicketId;
        //private bool isInChangeMode;
        private bool initiallyLoaded;
        private readonly ICeremonyService ceremonyService;
        private List<ValueIdPair> ceremonyLanguages;
        private List<ValueIdPair> certificateLanguages;
        private List<CeremonySpecialNeed> ceremonyspecialNeeds;

        private readonly IEventAggregator eventAggregator;

        public TabItemCeremonyView(ICeremonyService service, IEventAggregator aggregator)
        {
            ceremonyService = service;
            eventAggregator = aggregator;
            Initialized += TabItemCeremonyView_Initialized;
            InitializeComponent();

            KeyUp += UserControl_KeyUp;
            Loaded += TabItemCeremonyView_Loaded;
            DataContextChanged += TabItemCeremonyView_DataContextChanged;
            InterpreterCheckBox.Checked += InterpreterCheckBox_Checked;
            InterpreterCheckBox.Unchecked += InterpreterCheckBox_Unchecked;
            SpecialNeedsRadioButtonList.SelectionChanged += SpecialNeedsRadioButtonList_SelectionChanged;
            CertificateLanguagesComboBox.SelectionChanged += CertificateLanguagesComboBox_SelectionChanged;
            IssuedDateTextBox.SelectedDateChanged += IssuedDateTextBox_SelectedDateChanged;
            HPLatestDateTextBox.SelectedDateChanged += HPLatestDateTextBox_SelectedDateChanged;

            PreviewLostKeyboardFocus += TabItemCeremonyView_PreviewLostKeyboardFocus;
            
            // We need to initialize in order to set the tab name properly
            //Model = service.GetCeremony(loadedTicketId);
        }

        private void UpdateChangeMode()
        {
            if (Model != null && initiallyLoaded) Model.IsInChangeMode = true;
        }

        private void TabItemCeremonyView_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var newfocus = e.NewFocus;
            if(newfocus.GetType() == typeof(TabItem))
            {
                var tabItem = (TabItem) newfocus;
                if (!tabItem.Header.ToString().Equals(HeaderNames.Ceremony))
                {
                    //Byte till annan tab
                    e.Handled = HandleChange();
                }
            }
            if (newfocus.GetType() == typeof(ListViewItem))
            {
                var listViewItem = (ListViewItem)newfocus;
                if (listViewItem.Content != null &&
                    listViewItem.Content is CouplesSummaryItem)
                {
                    //Assume it's the couples list view 
                    e.Handled = HandleChange();
                }
            }
        }

        private bool HandleChange()
        {
            if (Model.IsInChangeMode)
            {
                var result = MessageBox.Show(Properties.Resources.UnsavedChanges, "Information", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                if (result == MessageBoxResult.Yes)
                {
                    ToggleMode(false);
                }
                else
                {
                    return true;
                }
            }
            return false;
        }

        #region ICeremonyView Members

        public CeremonyPresentationModel Model
        {
            get { return DataContext as CeremonyPresentationModel; }
            set { DataContext = value; }
        }

        private int selectedTicketId;
        public int SelectedTicketId
        {
            get { return selectedTicketId; }
            set
            {
                selectedTicketId = value;
                if (IsLoaded && loadedTicketId != SelectedTicketId)
                {
                    initiallyLoaded = false;
                    Model = ceremonyService.GetCeremony(selectedTicketId);
                    loadedTicketId = selectedTicketId;
                }
            }
        }

        #endregion

        private void TabItemCeremonyView_Initialized(object sender, EventArgs e)
        {
            ceremonyLanguages = ceremonyService.GetCeremonyLanguages();
            certificateLanguages = ceremonyService.GetCertificateLanguages();
            ceremonyspecialNeeds = ceremonyService.GetSpecialNeeds();

            SpecialNeedsRadioButtonList.ItemsSource = ceremonyspecialNeeds;
            CeremonyLanguagesRadioButtonList.ItemsSource = ceremonyLanguages;
            CertificateLanguagesComboBox.ItemsSource = certificateLanguages;
            initiallyLoaded = true;
        }

        private void ToggleButtons()
        {
            UpdateChangeMode();
        }

        private void SetSelectedItems()
        {
            var model = DataContext as CeremonyPresentationModel;

            if (model == null)
                return;

            if (model.CertificateLanguage != null)
            {
                CertificateLanguagesComboBox.SelectedValue =
                    certificateLanguages.Where(l => l.Name == model.CertificateLanguage.Name).FirstOrDefault();
            }

            if (model.CeremonyLanguage != null)
            {
                CeremonyLanguagesRadioButtonList.SelectedItem =
                    ceremonyLanguages.Where(l => l.Name == model.CeremonyLanguage.Name).FirstOrDefault();
            }

            CeremonySpecialNeed[] specialNeeds = null;
            if (model.CeremonySpecialNeeds != null)
            {
                //Får skapa en kopia här då UpdateSpecialNeeds() gör att vi tömmer model.CeremonySpecialNeeds
                //och då får vi ett exception
                specialNeeds = model.CeremonySpecialNeeds.ToArray<CeremonySpecialNeed>();
            }
            SpecialNeedsRadioButtonList.SelectedItems.Clear();
            if (specialNeeds != null)
            {
                foreach (var item in specialNeeds)
                {
                    var selectedItem = FindItem(item.Name);

                    if (selectedItem != null)
                        SpecialNeedsRadioButtonList.SelectedItems.Add(selectedItem);
                }
            }
            if(model.HPIssuedDate.HasValue)
            {
                HPHasArrivedCheckBox.IsChecked = true;
            }
        }

        private void TabItemCeremonyView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var model = DataContext as CeremonyPresentationModel;

            if (model == null)
                return;
            
            SetSelectedItems();

            if(loadedTicketId != selectedTicketId)
                ToggleMode(false);
        }

        private void TabItemCeremonyView_Loaded(object sender, RoutedEventArgs e)
        {
            Model = selectedTicketId == 0 ? ceremonyService.InitializeNewCeremony() : ceremonyService.GetCeremony(selectedTicketId);
            loadedTicketId = selectedTicketId;
            Model.IsInChangeMode = false;
        }

        private void IssuedDateTextBox_SelectedDateChanged(object sender, EventArgs e)
        {
            HPHasArrivedCheckBox.IsChecked = IssuedDateTextBox.SelectedDate.HasValue;
            UpdateChangeMode();
        }
        private void HPLatestDateTextBox_SelectedDateChanged(object sender, EventArgs e)
        {
           UpdateChangeMode();
        }
        private void InterpreterCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            ToggleButtons();
        }

        private void InterpreterCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            ToggleButtons();
        }

        private void SpecialNeedsRadioButtonList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ToggleButtons();
            UpdateSpecialNeeds(); 
            e.Handled = true;
        }

        private void CertificateLanguagesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ToggleButtons();
        }

        // bugg, hur f-n sätter man items till selected egentligen????
        private ValueIdPair FindItem(string name)
        {
            foreach (var item in SpecialNeedsRadioButtonList.Items)
            {
                var selected = item as ValueIdPair;
                if (selected != null && selected.Name == name)
                    return selected;
            }

            return null;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait; 
            
            var model = DataContext as CeremonyPresentationModel;

            if (model == null)
                return;

            BindingExpression be = HPHasArrivedCheckBox.GetBindingExpression(ToggleButton.IsCheckedProperty);
            be.UpdateSource();

            be = HPEarliestTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            //be = HPLatestDateTextBox.GetBindingExpression(DateTimePicker.SelectedDateProperty);
            //be.UpdateSource();

            //be = IssuedDateTextBox.GetBindingExpression(DateTimePicker.SelectedDateProperty);
            //be.UpdateSource();

            model.HPLatestDate = HPLatestDateTextBox.SelectedDate;
            model.HPIssuedDate = IssuedDateTextBox.SelectedDate;

            // Bugg bugg bugg!!!!!! 
            //be = CeremonyLanguagesRadioButtonList.GetBindingExpression(Selector.SelectedItemProperty);
            //be.UpdateSource();
            model.CeremonyLanguage = (ValueIdPair)CeremonyLanguagesRadioButtonList.SelectedItem;

            be = OtherLanguageTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            be = InterpreterCheckBox.GetBindingExpression(ToggleButton.IsCheckedProperty);
            be.UpdateSource();

            be = CertificateLanguagesComboBox.GetBindingExpression(Selector.SelectedItemProperty);
            be.UpdateSource();

            // Ska man kunna lägga till förrättare?? Isf ska dessa inte kommenteras bort
            //be = MinisterFirstNameTextBox.GetBindingExpression(TextBox.TextProperty);
            //be.UpdateSource();

            //be = MinisterLastNameTextBox.GetBindingExpression(TextBox.TextProperty);
            //be.UpdateSource();

            UpdateSpecialNeeds();

            be = NoteTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            model.SaveCommand.Execute(model);
            ToggleMode(false);

            Mouse.OverrideCursor = null;
        }

        private void UpdateSpecialNeeds()
        {
            var model = DataContext as CeremonyPresentationModel;

            if (model == null)
                return;

            // Ännu ett hack för att få multiple combobox att funka....
            if (SpecialNeedsRadioButtonList.SelectedItems != null)
            {
                model.CeremonySpecialNeeds = new List<CeremonySpecialNeed>();
                foreach (CeremonySpecialNeed item in SpecialNeedsRadioButtonList.SelectedItems)
                {
                    model.CeremonySpecialNeeds.Add(item);
                }
            }
        }

        private void ChangeButton_Click(object sender, RoutedEventArgs e)
        {
            ToggleMode(true);

            //Moved to Model
            //eventAggregator.GetEvent<IsInChangeModeEvent>().Publish(Model.TicketId.ToString());
        }

        private void ToggleMode(bool enabled)
        {
            Model.IsInChangeMode = enabled;
         }

        //private void CancelButton_Click(object sender, RoutedEventArgs e)
        //{
        //    SpecialNeedsRadioButtonList.SelectedItems.Clear();

        //    var model = DataContext as CeremonyPresentationModel;

        //    if (model == null)
        //        return;

        //    HPHasArrivedCheckBox.IsChecked = model.HPHasArrived;
        //    HPEarliestTextBox.Text = model.HPEarliestDate.HasValue
        //                                 ? model.HPEarliestDate.Value.ToString("yyyy-MM-dd")
        //                                 : "";

        //    HPLatestDateTextBox.SelectedDate = model.HPLatestDate.HasValue ? model.HPLatestDate.Value : new DateTime();

        //    IssuedDateTextBox.SelectedDate = model.HPIssuedDate.HasValue ? model.HPIssuedDate.Value : new DateTime();

        //    HPHasArrivedCheckBox.IsChecked = model.HPIssuedDate.HasValue ? true : false;

        //    CeremonyLanguagesRadioButtonList.SelectedValue = model.CeremonyLanguage;
        //    OtherLanguageTextBox.Text = model.OtherLanguage;
        //    InterpreterCheckBox.IsChecked = model.Interpreter;
        //    CertificateLanguagesComboBox.SelectedValue = model.CertificateLanguage;
        //    MinisterFirstNameTextBox.Text = model.MinisterFirstName;
        //    MinisterLastNameTextBox.Text = model.MinisterLastName;

        //    //SpecialNeedsRadioButtonList
        //    SetSelectedItems();

        //    NoteTextBox.Text = model.Note;

        //    ToggleButtons();
        //}

        private void UserControl_KeyUp(object sender, KeyEventArgs e)
        {
            ToggleButtons();
            e.Handled = true;
        }

        private void OtherLanguageTextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (OtherLanguageTextBox.Text != "")
            {
                //Om man efterfrågar annat språk så ändra Ceremonispråk till Engelska
                //CeremonyLanguagesRadioButtonList.SelectedItem =
                //    ceremonyLanguages.Where(l => l.Name == "Engelska").FirstOrDefault();
            }
        }

    }
}
